package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.beans.AccountBean;
import com.moyun.zbmy.zizhou.beans.AccountNewsArticleBean;
import com.moyun.zbmy.zizhou.beans.AccountNewsItem;
import com.moyun.zbmy.zizhou.beans.FComment;
import com.moyun.zbmy.zizhou.beans.ImageBean;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.http.ParamsEditor;
import com.moyun.zbmy.zizhou.ui.adapter.AccountPicAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionMoreImgNewsHolder;
import com.moyun.zbmy.zizhou.ui.utils.GlideCircleTransform;
import com.moyun.zbmy.zizhou.ui.utils.GlideUtil;
import com.moyun.zbmy.zizhou.ui.utils.SampleListener;
import com.moyun.zbmy.zizhou.ui.utils.SkipUtil;
import com.moyun.zbmy.zizhou.ui.widget.BasePlayerView;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountNewsDetail;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 互动号 爆料类型详情
 */
public class AccountKnockOutDetailActivity extends BaseAccountActivity {

    @BindView(R.id.account_layout)
    protected RelativeLayout account_layout;
    @BindView(R.id.account_avatar)
    protected ImageView accountAvatar;
    @BindView(R.id.account_name)
    protected CustomFontTextView accountName;
    @BindView(R.id.account_time)
    protected CustomFontTextView accountTime;
    @BindView(R.id.account_subscribe)
    protected ImageView accountSubscribe;

    @BindView(R.id.account_news_content)
    protected CustomFontTextView accountNewsContent;
    @BindView(R.id.imgs_layout)
    protected RelativeLayout imgsLayout;
    @BindView(R.id.pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.video_layout)
    protected RelativeLayout videoLayout;
    @BindView(R.id.video_img)
    protected ImageView videoImg;
    @BindView(R.id.news_detail_player)
    protected BasePlayerView videoPlayer;
    @BindView(R.id.comment_layout_number)
    protected CustomFontTextView commentNumber;
    @BindView(R.id.comment_layout_doup)
    protected CustomFontTextView commentDoup;
    @BindView(R.id.comment_layout_share)
    protected CustomFontTextView shareBtn;
    public static int REQUEST_COMMENT_CODE = 505;
    public static final String NEWS_BEAN = "news_bean";
    private Handler handler;
    private int capacity = 5;//请求数据条数
    private int indexNumber = 0;
    private int commentCount = 0;//评论数
    private AccountNewsItem newsItem;
    private GridLayoutManager manager;
    private AccountPicAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        videoPlayer.setMute(true);
        getDetailData();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_account_knock_out_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.setMute(videoPlayer.isMute());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
        }
    }

    private void getDetailData() {
        Serializable se = getIntent().getSerializableExtra(NEWS_BEAN);
        if (se instanceof AccountNewsItem) {
            newsItem = (AccountNewsItem) se;
            initDetailData();
        }
    }


    private void initDetailData() {
        if (!TextUtils.isEmpty(newsItem.getShareURL())) {
            shareBtn.setVisibility(View.VISIBLE);
        }
        account_layout.setVisibility(View.VISIBLE);
        accountNewsContent.setText(newsItem.getNewsDetailText());
        GlideUtil.getCircleGlid(this, newsItem.getFollowedSmallImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .transform(new GlideCircleTransform(this)).into(accountAvatar);
        accountName.setText(newsItem.getFollowedName());
        String timeStr = DateUtils.formatDate(DateUtils.getDataDate(newsItem), "");
        accountTime.setText(timeStr);
        if (newsItem.getFollowedStatus() == 1) {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
        } else {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
        }
        if (newsItem.getNewsDetailType() == 102 && !TextUtils.isEmpty(newsItem.getNewsDetailVideo())) {
            videoLayout.setVisibility(View.VISIBLE);
//            GlideUtil.getGlideWithSmall169DefCenterCrop(this, newsItem.getNewsDetailSmallImage()).into(videoImg);
//            videoLayout.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (null != newsItem) {
//                        SkipUtil.skipToVideoPlay(AccountKnockOutDetailActivity.this, UrlUtils.linkUrls(Constances.ST_BASE_URL, newsItem.getNewsDetailVideo()), newsItem.getNewsDetailSmallImage());
//                    }
//                }
//            });

            VideoInfo videoInfo = new VideoInfo("");
            videoInfo.Cdn = "cdn";
            videoInfo.VideoOriginalName = newsItem.getNewsDetailText();
            videoInfo.VideoName = newsItem.getNewsDetailText();
            videoInfo.VideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, newsItem.getNewsDetailVideo());
            videoInfo.extendProperty1 = "直播三台APP_Android";
            try {
                videoInfo.extendProperty1 = "直播三台APP_Android_" + getApplicationContext().getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            videoInfo.extendProperty1 = NetUtils.GetNetName(this);
            videoInfo.setVideoWebChannel("///");
            initVideoPlayer(videoPlayer, videoInfo, false);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    int netType = NetModeUtil.GetNetype(AccountKnockOutDetailActivity.this);
                    actionPlay(videoPlayer, UrlUtils.linkUrls(Constances.ST_BASE_URL, newsItem.getNewsDetailVideo())
                            , newsItem.getNewsDetailTitle(), newsItem.getNewsDetailSmallImage(), netType == 1);
                }
            }, 100);

        }
        if (null != newsItem) {
            if (newsItem.isNewsDetailAttitudesStatus()) {
                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                commentDoup.setDrawables(drawable, null, null, null);
                commentDoup.setTextColor(getResources().getColor(R.color.colorTxRedMain_));
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                commentDoup.setDrawables(drawable, null, null, null);
                commentDoup.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));
            }
            commentDoup.setText("" + newsItem.getNewsDetailAttitudesCount());
        }
        if (ListUtils.isListValued(newsItem.getNewsDetailImages())) {
            //多图
            imgsLayout.setVisibility(View.VISIBLE);
            initView(newsItem.getNewsDetailImages());

        } else {
            //无图
            imgsLayout.setVisibility(View.GONE);
        }
        refreshBottomCommentShowing(newsItem.getNewsDetailCommentCount());
    }

    private void initView(List<ImageBean> dataImgs) {
        manager = new GridLayoutManager(this, 3);

        pic_list.setItemAnimator(new DefaultItemAnimator());
        pic_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        if (adapter == null) {
            // new UiListMarginUtils().setMargin(context, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
            adapter = new AccountPicAdapter(this, dataImgs);
        } else {
            adapter.setData(dataImgs);
        }
        pic_list.setAdapter(adapter);
    }

    /**
     * 刷新评论数据
     *
     * @param count
     */
    private void refreshBottomCommentShowing(long count) {
        String str = getString(R.string.detail_comment_no);
        if (count > 0) {
            if (count > 99) {
                str = getString(R.string.detail_comment_counts);
            } else {
                str = getString(R.string.detail_comment_count, count);
            }
        }
        commentNumber.setText(str);
    }

    @OnClick(value = {R.id.title_top_back, R.id.account_subscribe, R.id.comment_layout_write_comment, R.id.comment_layout_number, R.id.comment_layout_doup, R.id.comment_layout_share})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                finish();
                break;
            case R.id.account_subscribe:
                //TODO 关注、取消关注
                if (null != newsItem) {
                    if (null != UserManager.getInstance().getUser()) {
                        setResult(RESULT_OK);
                        toAttentionClick(newsItem.getFollowedStatus());
                    } else {
                        toLogin();
                    }
                }
                break;
            case R.id.comment_layout_write_comment:
                String newid = "" + newsItem.getNewsDetailId();
                showCommentDialog(newid,newsItem.getNewsDetailTitle() ,null, 0);  //0代表新闻评论
                setResult(RESULT_OK);
                break;
            case R.id.comment_layout_number:
                if (newsItem.getNewsDetailCommentCount() != 0) {
                    Intent intent = new Intent(this, CommentActivity.class);
                    String id = "" + newsItem.getNewsDetailId();
                    intent.putExtra(EX_ID, id);
                    intent.putExtra(EX_TYPE_NEWS, Constances.REQUEST_COMMENT_TYPE_NEWS);
                    intent.putExtra(EX_COMMENT_TYPE, 0);
                    startActivityForResult(intent, REQUEST_COMMENT_CODE);
                    setResult(RESULT_OK);
                }
                break;
            case R.id.comment_layout_doup:
//                setResult();
                newsDoUp();
                break;
            case R.id.comment_layout_share:
                if (!TextUtils.isEmpty(newsItem.getShareURL())) {
                    this.setNewsId("" + newsItem.getNewsDetailId());
                    showShareFragment(newsItem, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
        }
    }


    /**
     * 处理 关注或取消关注
     *
     * @param isAttention
     */
    private void toAttentionClick(int isAttention) {
        if (isAttention == 1) {
            toUnAttentionAccount("" + newsItem.getFollowedId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    newsItem.setFollowedStatus(0);
                    accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                }
            });
        } else {
            toAttentionAccount("" + newsItem.getFollowedId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    newsItem.setFollowedStatus(1);
                    accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

    /**
     * 点赞、取消点赞请求
     */
    private void newsDoUp() {
        final String newId = "" + newsItem.getNewsDetailId();
        if (UserManager.isLoginS()) {
            commentDoup.setDrawableEnlarge();
            ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
            pe.put("dynamicId", newId);
            pe.put("fType", 3);//1 主播 2报料 3新闻 4 直播 5视频
//        pe.put("token", UserManager.getInstance().getToken());
            pe.put("userId", UserManager.getInstance().getUser().getUserId());

            NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
                @Override
                public void onSuc(SingleResult singleResult) {
                    if (singleResult.isSuccess()) {
                        if (null != newsItem) {
                            if (newsItem.isNewsDetailAttitudesStatus()) {
                                newsItem.setNewsDetailAttitudesStatus(!newsItem.isNewsDetailAttitudesStatus());
                                newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() - 1);
                            } else {
                                newsItem.setNewsDetailAttitudesStatus(!newsItem.isNewsDetailAttitudesStatus());
                                newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() + 1);
                            }

                            if (newsItem.isNewsDetailAttitudesStatus()) {
                                Drawable drawable = AccountKnockOutDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                commentDoup.setDrawables(drawable, null, null, null);
                                commentDoup.setTextColor(AccountKnockOutDetailActivity.this.getResources().getColor(R.color.colorTxRedMain_));
                            } else {
                                Drawable drawable = AccountKnockOutDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                commentDoup.setDrawables(drawable, null, null, null);
                                commentDoup.setTextColor(AccountKnockOutDetailActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                            }
                            commentDoup.setText("" + newsItem.getNewsDetailAttitudesCount());
                            if (newsItem.isNewsDetailAttitudesStatus()) {
                                addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                            }
                        }
                        setResult(RESULT_OK);
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg, int netCode) {
                    super.onError(ex, errorMsg, netCode);
                }
            });

        } else {
            toLogin();
        }
    }

    @Override
    protected void initVideoPlayer(@NonNull BasePlayerView player, VideoInfo info, boolean isLiving) {
        super.initVideoPlayer(player, info, false);
        player.setIsTouchWiget(false);
        setSampleVideoListener(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                JLog.e("aasa   in prepare");

                if (!isAutoRotation()) {
                    setAutoRotation(true);
                }
            }

            @Override
            public void onClickStop(String url, Object... objects) {
                super.onClickStop(url, objects);
                JLog.e("aasa   in click stop");
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
                JLog.e("aasa   in auto complete");
            }

            @Override
            public void onPlayError(String url, Object... objects) {
                super.onPlayError(url, objects);
                JLog.e("aasa   in error");
            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {
                super.onClickStartIcon(url, objects);
                JLog.e("aasa   in click start icon");
            }

            @Override
            public void onClickResume(String url, Object... objects) {
                super.onClickResume(url, objects);
                JLog.e("aasa   in clickResume");

                if (!isAutoRotation()) {
                    setAutoRotation(true);
                }
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        videoPlayer.setFocusable(true);
        videoPlayer.setFocusableInTouchMode(true);
        videoPlayer.requestFocus();
    }

    @Override
    public void onNetPromptCallBacked(boolean isContinue) {
        if (isContinue) {
//            StandardGSYVideoPlayer player = getVideoPlayer();
            if (videoPlayer != null) {
                videoPlayer.startPlayLogic();
            }
        }
    }

    @Override
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
        if (indexNumber >= count || count <= capacity) {
            commentCount = count;
            refreshBottomCommentShowing(count);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_LOGIN) {
                getDetailData();
                setResult(RESULT_OK);
            } else if (requestCode == REQUEST_COMMENT_CODE) {
                getCommentNews("" + newsItem.getNewsDetailId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
            }
        }
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        getCommentNews("" + newsItem.getNewsDetailId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
            videoPlayer = null;
        }
    }
}

